<template>
  <div class="Infom">
    <van-nav-bar title="商品详情" left-arrow left-text="返回" @click-left="$goBack" />

    <!-- 判断数据是否加载完成 -->
    <div>
      <img :src="infomData.goodsCoverImg" alt="商品图片">
      <h3>{{ infomData.goodsName }}</h3>
      <p>{{ infomData.goodsIntro }}</p>
      <p style="color: #999;">免邮费 顺丰快递</p>
      <span id="fc">￥{{ infomData.sellingPrice }}</span>

      <div class="button-group">
        <van-button class="but1" @click="joinShopCar">加入购物车</van-button>
        <van-button class="but2" @click="pushCar">立即购买</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant';
export default {
  props: {
    goodsId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      infomData: null, // 商品详情数据
    };
  },
  created() {
    this.loadProductDetails(); // 创建时立即加载商品详情
  },
  methods: {
    loadProductDetails() {
      const goodsId = this.goodsId;
      const indexData = this.$root.indexData;
      const allGoods = [
        ...indexData.hotGoodses,
        ...indexData.newGoodses,
        ...indexData.recommendGoodses,
      ];
      // 查找对应的商品
      const product = allGoods.find(item => item.goodsId === parseInt(goodsId));
      if (product) {
        this.infomData = product;
      }
    },
    joinShopCar() {
      if (this.infomData) {
        // 创建一个包含quantity属性的商品对象副本
        const productWithQuantity = { ...this.infomData, quantity: 1 };
        // 发送商品数据到购物车页面
        this.$store.dispatch('addToCart', productWithQuantity);

        Toast.success('已加入购物车');
      }
    },
    pushCar() {
    this.$router.push('/shopCar'); // 跳转到购物车页面
  }
  },
};
</script>

<style scoped lang="less">
.Infom {
  text-align: center;
}

#fc {
  color: #ff0000;
}

img {
  width: 200px;
  height: 200px;
}

p {
  margin-left: 15px;
  text-align: left;
  font-size: 14px;
}

span {
  margin-left: 15px;
  display: block;
  text-align: left;
  font-size: 18px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 180px;
}

.but1 {
  background-color: #87CEEB; // 浅蓝色背景
  color: white;
  border: none;
  border-radius: 25px 0 0 25px; // 左半边圆角
  padding: 10px 20px;
  flex: 1;
  margin-left: 10px;
}

.but2 {
  background-color: #00CED1; // 深蓝色背景
  border: none;
  border-radius: 0 25px 25px 0; // 右半边圆角
  padding: 10px 20px;
  flex: 1;
  margin-right: 10px;
  color: white;
}
</style>
